<template>
  <div
    class="ky-tree-filter"
  >
    <el-input
      class="ky-mb10"
      size="small"
      clearable
      placeholder="输入关键字进行过滤"
      v-model="filterText">
    </el-input>
    <div
      ref="kyTreeWrap"
      class="ky_tree_wrap"
      :style="twStyle"
    >
      <el-tree
        class="filter-tree"
        :data="treeData"
        :props="defaultProps"
        default-expand-all
        highlight-current
        check-on-click-node
        :expand-on-click-node="false"
        node-key="id"
        :filter-node-method="filterNode"
        @current-change="currentChange"
        ref="treeFilter">
      </el-tree>
    </div>
  </div>
</template>

<script>
export default {
  name: 'KyTreeFilter',
  props: {
    topHeight: {
      type: Number,
      default: 320
    },
    treeData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      filterText: '',
      twStyle: { height: 'calc(100vh - 320px)' },
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.treeFilter.filter(val)
    },
    treeData: {
      handler(val, oldVal) {
        this.resetChecked()
      },
      deep: true
    }
  },
  mounted() {
    this.$_resizeHandler_treeWrap()
  },
  methods: {
    resetChecked(val) {
      this.filterText = ''
      this.$refs.treeFilter.setCurrentKey(val)
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    currentChange(value, node) {
      this.$emit('treeChange', value.id)
    },
    $_resizeHandler_treeWrap() {
      const twRef = this.$refs.kyTreeWrap
      if (twRef) {
        this.$nextTick(() => {
          // this.fscHeight = twRef.getBoundingClientRect().top + 25
          this.twStyle.height = `calc(100vh - ${twRef.getBoundingClientRect().top + 40}px)`
        })
      }
    }
  },
  beforeMount() {
    window.addEventListener('resize', this.$_resizeHandler_treeWrap)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.$_resizeHandler_treeWrap)
  }
}
</script>

<style lang="scss" scoped>
.ky-tree-filter{
  height: 100%;
}
.ky_tree_wrap{
  overflow-y: auto;
}
/deep/ .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content{
  background-color: #00C0EF;
  color: #fff;
}
</style>
